import { DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, message,Divider,Row,Col,Card,Form,Input,InputNumber,Radio,Tree,Empty} from 'antd';
import React, { useState, useRef,useEffect} from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { connect, history } from 'umi';
import { resourcePage,addResource,removeResource,updateResource} from './service';
import db from '@/utils/localstorage';
import SuperIcon from '@/components/SuperIcon';
import styles from './style.less';
import {HasPermission} from '@/components/AuthComponent/HasPermission';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
const AuthButton = HasPermission(Button);
const AuthDivider = HasPermission(Divider);

const FormItem = Form.Item;
const { TreeNode } = Tree;

const formItemLayout = {
  labelCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 4,
    },
  },
  wrapperCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 16,
    },
    md: {
      span: 16,
    },
  },
};
const submitFormLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0,
    },
    sm: {
      span: 10,
      offset: 4,
    },
  },
};
/**
 *  删除节点
 * @param selectedRows
 */

const handleRemove = async selectedRows => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await batchRemoverole({
      ids: selectedRows.map(row => row.id),
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};


const AuthMenu = props => {
  const {dispatch,currentItem,submitting, menuTree,selectedKeys,checkedKeys} =props
  const [dictTypeList, setDictTypeList] = useState(db.get("dictTypeList")['yes_no']);
  const [modalVisible, setModalVisible] = useState(false);
  const [modalUpdateVisible, setModalUpdateVisible] = useState(false);
  const [formValues, setFormValues] = useState({});
  const actionRef = useRef();
  const [form] = Form.useForm();
  const createColumns = [
    {
      title: '编码',
      dataIndex: 'perms',
      key:'perms',
      rules:[
        {
          required: true,
          message: '请输入编码',
        },
      ],
    },
    {
      title: '名称',
      dataIndex: 'name',
      key:'name',
      rules:[
        {
          required: true,
          message: '请输入名称',
        },
      ],
    },
  ];

  const updateColumns = [
    {
      title: '编码',
      dataIndex: 'perms',
      key:'perms',
      initialValue:formValues.perms||"",
      rules:[
        {
          required: true,
          message: '请输入编码',
        },
      ],
    },
    {
      title: '名称',
      dataIndex: 'name',
      initialValue:formValues.name||"",
      key:'name',
      rules:[
        {
          required: true,
          message: '请输入名称',
        },
      ],
    },
  ];
  const columns = [
    {
      title: '编码',
      dataIndex: 'perms',
      hideInSearch:true
    },
    {
      title: '名称',
      dataIndex: 'name',
      hideInSearch:true
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <AuthButton auth={[`menu:resource:update`]} type="link"  onClick={() => handleUpdateModalVisible(record)}>编辑</AuthButton>
           <AuthDivider auth={['menu:resource:delete',`menu:resource:update`]} type="vertical"></AuthDivider>
           <AuthButton auth={['menu:resource:delete']} type="link"  onClick={() => handleDelete(record)}>删除</AuthButton>
        </>
      ),
    },
  ];

  useEffect(() => {
    if (dispatch) {
      dispatch({
        type: 'cubeMenu/menuTree',
        payload: {},
      })
     }
   }, []);

   /**
    * 编辑按钮权限
    * @param {*} record 
    */
   const handleUpdateModalVisible = async record =>{
    setFormValues(record)
    setModalUpdateVisible(true)
   }

   /**
    * 删除按钮权限
    * @param {*} record 
    */
   const handleDelete = async record =>{
    const hide = message.loading('正在删除');
    try {
     let result = await removeResource({ ids:[record.menuId] });
     if(result.code===0){
      hide();
      message.success('删除成功，即将刷新');
      actionRef.current.reload();
      return true;
     }else{
      hide();
      message.error(result.errmsg);
      return false;
     }
    } catch (error) {
      hide();
      message.error('删除失败，请重试！');
      return false;
    }
   }
   
   /**
   * 新增
   * @param {*} async 
   */
  const goToSave = async  => {
    setModalVisible(true)
  };


  const onFinish = async () => {
    const values = await form.validateFields();
    let params={}
    if(values.hideInMenu=='1'){
      values.hideInMenu=true
    }else{
      values.hideInMenu=false
    }
    if(currentItem&&currentItem.menuId){
      //编辑
      params={
        ...currentItem,
        ...values,
        type:values.parentId==0?0:1
      }
    }else{
      //新增
      params={
        ...values,
        type:values.parentId==0?0:1
      }
    }
    const hide = message.loading('正在保存');
    try {
     let result ;
     if(currentItem&&currentItem.menuId){
      result = await updateResource({ ...params})
     }else{
      result = await addResource({ ...params})
     }
     if(result.code===0){
      hide();
      message.success('保存成功，即将刷新');
      dispatch({
        type: 'cubeMenu/menuTree',
        payload: {},
      })
      return true;
     }else{
      hide();
      message.error(result.message);
      return false;
     }
    } catch (error) {
      hide();
      message.error('保存失败，请重试！');
      return false;
    }
  };

  /**
   * 渲染树
   * @param {*} data 
   */
  const renderTreeNodes = data =>
    data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={item.name} key={item.menuId} dataRef={item} icon={<div>
            {item.icon!=''?<SuperIcon type={item.icon} />:<SuperIcon type="icon-wenjianfile63" />}
            </div>}>
            {renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
    return <TreeNode key={item.menuId} title={item.name} {...item} dataRef={item} icon={<div>
      {item.icon!=''?<SuperIcon type={item.icon} />:<SuperIcon type="icon-wenjianfile63" />}
      </div>} />;
  });

  /**
   * 树节点选择
   */
  const onSelect =(selectedKeys, e) =>{
    const { dispatch } =props
    let selected = e.selected;
    if(selected){
      let node=e.node.props.dataRef;
      dispatch({
        type: 'cubeMenu/commonEffect',
        payload:{
          currentItem:node,
        }
      }).then(()=>{
        form.resetFields()
      })
      if(selectedKeys&&selectedKeys.length>0){
        dispatch({
          type: 'cubeMenu/commonEffect',
          payload:{
            selectedKeys:selectedKeys,
          }
        }).then(()=>{
          actionRef.current.reload();
        })
      }
    }else{
      dispatch({
        type: 'cubeMenu/commonEffect',
        payload:{
          currentItem:{},
          selectedKeys:[],
        }
      }).then(()=>{
        form.resetFields()
        actionRef.current.reload();
      })
    }
  }
  /**
   *  树节点check
   */
  const onCheck = (checkedKeys, e) =>{
    dispatch({
      type: 'cubeMenu/commonEffect',
      payload:{
        checkedKeys:checkedKeys.checked
      }
    });
  }

  /**
   * 新增菜单
   */
  const addMenu = () =>{
    if(selectedKeys&&selectedKeys.length>0){
      dispatch({
        type: 'cubeMenu/commonEffect',
        payload:{
          currentItem:{
            parentId:selectedKeys[0]
          }
        }
      }).then(()=>{
        form.resetFields()
      })
    }else{
      dispatch({
        type: 'cubeMenu/commonEffect',
        payload:{
          currentItem:{
            parentId:0
          }
        }
      }).then(()=>{
        form.resetFields()
      })
    }
  }

  /**
   * 删除菜单
   */
  const delMenu = async ()=>{
    if(!checkedKeys||checkedKeys.length==0){
      message.warn('未选中需要删除的菜单')
      return;
    }
    const hide = message.loading('正在删除');
    try {
     let result = await removeResource({ ids:checkedKeys});
     if(result.code===0){
      hide();
      message.success('删除成功，即将刷新');
      dispatch({
        type: 'cubeMenu/menuTree',
        payload: {},
      })
      return true;
     }else{
      hide();
      message.error(result.message);
      return false;
     }
    } catch (error) {
      hide();
      message.error('删除失败，请重试！');
      return false;
    }
  }
 /**
 * 添加节点
 * @param fields
 */
const handleAdd = async fields => {
  if(selectedKeys&&selectedKeys.length>0){
    const hide = message.loading('正在添加');
    try {
     let result = await addResource({ ...fields,parentId:selectedKeys[0],type:2 });
     if(result.code===0){
      hide();
      message.success('添加成功，即将刷新');
      setModalVisible(false)
      return true;
     }else{
      hide();
      message.error(result.errmsg);
      return false;
     }
    } catch (error) {
      hide();
      message.error('添加失败，请重试！');
      return false;
    }
  }else{
    message.warn('请先选择需要添加资源的菜单');
  }
};
/**
 * 编辑权限按钮
 * @param {*} fields 
 */
const handleUpdate = async fields => {
  const hide = message.loading('正在编辑');
    try {
     let result = await updateResource({ ...formValues,...fields });
     if(result.code===0){
      hide();
      message.success('编辑成功，即将刷新');
      setModalVisible(false)
      setFormValues({})
      return true;
     }else{
      hide();
      message.error(result.errmsg);
      return false;
     }
    } catch (error) {
      hide();
      message.error('编辑失败，请重试！');
      return false;
    }
};
  return (
    <PageHeaderWrapper>
      <Row gutter={12}>
        <Col xs={24} sm={6}>
          <Card bordered={false}>
            <div className={styles.search}>
                <div className={styles.opt}> 
                  <AuthButton auth={[`menu:add`]} type="primary" icon={<PlusOutlined/>} onClick={addMenu} >新增</AuthButton>
                  <AuthButton auth={[`menu:delete`]} type="danger" icon={<DeleteOutlined />} onClick={delMenu} >删除</AuthButton>
                </div>
              </div>
          {
                menuTree&&menuTree.length?<Tree
                 showIcon
                 checkable
                 autoExpandParent
                 defaultExpandAll
                 onSelect={onSelect}
                 onCheck={onCheck}
                 selectedKeys={selectedKeys}
                 checkedKeys={checkedKeys}
                 checkStrictly={true}
                 blockNode={true}
               >
                {renderTreeNodes(menuTree)}
               </Tree>:<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
              }
          </Card>
        </Col>
        <Col xs={24} sm={8}>
          <Card bordered={false} title={currentItem.id?"修改":"新增"}> 
              <Form
                style={{
                  marginTop: 8,
                }}
                form={form}
                name="basic"
                initialValues={{
                  ...currentItem,
                  hideInMenu:currentItem.hideInMenu?"1":"2"
                }}
              >
                <FormItem
                    {...formItemLayout}
                    label="父ID"
                    name="parentId"
                  >
                    <Input placeholder="请输入" disabled/>
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="菜单名称"
                    name="name"
                  >
                    <Input placeholder="请输入"/>
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="路由"
                    name="routerUrl"
                  >
                    <Input placeholder="请输入"/>
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="国际化"
                    name="locale"
                  >
                    <Input placeholder="请输入"/>
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="图标"
                    name="icon"
                  >
                    <Input placeholder="请输入"/>
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="是否隐藏"
                    name="hideInMenu"
                  >
                    <Radio.Group>
                      {
                        dictTypeList&&dictTypeList.map((item,index)=><Radio value={item.value} key={index}>{item.label}</Radio>)
                      }
                  </Radio.Group>
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="排序"
                    name="orderNum"
                  >
                    <InputNumber min={0} max={100} placeholder="请输入"/>
                </FormItem>
                <FormItem
                    {...submitFormLayout}
                    style={{
                      marginTop: 32,
                    }}
                  >
                    <AuthButton auth={[`menu:add`]} type="primary"  onClick={onFinish} loading={submitting}>
                    提交
                    </AuthButton>
                  </FormItem>
              </Form>
          </Card>
        </Col>
        <Col xs={24} sm={10}>
          <Card bordered={false}> 
                <ProTable
                    actionRef={actionRef}
                    rowKey="menuId"
                    toolBarRender={(action, { selectedRows }) => [
                      <AuthButton auth={[`menu:resource:add`]} type="primary" icon={<PlusOutlined />} onClick={() => goToSave()}>新增</AuthButton>
                    ]}
                    search={false}
                    request={params => {
                      let _params={
                        pageNum:params.current,
                        ...params,
                      }
                      if(selectedKeys&&selectedKeys.length>0){
                        _params.menuId=selectedKeys[0];
                      }
                      delete _params.current
                      return resourcePage(_params)
                    }}
                    columns={columns}
                  />
            </Card>
        </Col>
      </Row>
      <CreateForm modalVisible={modalVisible} onCancel={()=>setModalVisible(false)}>
        <ProTable
          onSubmit={async value => {
            const success = await handleAdd(value);

            if (success) {
              setModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          type="form"
          columns={createColumns}
          rowSelection={{}}
        />
      </CreateForm>
      <UpdateForm modalVisible={modalUpdateVisible} onCancel={()=>setModalUpdateVisible(false)}>
        <ProTable
          onSubmit={async value => {
            const success = await handleUpdate(value);

            if (success) {
              setModalUpdateVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          type="form"
          columns={updateColumns}
          rowSelection={{}}
        />
      </UpdateForm>
    </PageHeaderWrapper>
  );
};

export default connect(({ cubeMenu, loading }) => ({
  currentItem:cubeMenu.currentItem,
  menuTree: cubeMenu.menuTree,
  selectedKeys: cubeMenu.selectedKeys,
  checkedKeys: cubeMenu.checkedKeys,
  loading: loading.effects['cubeMenu/fetchVip'],
  submitting: loading.effects['cubeMenu/add'],
}))(AuthMenu);
